import { Injectable } from '@angular/core';
import { Action, NgxsAfterBootstrap, State, StateContext } from '@ngxs/store';
import { LogisticsService } from '../logistics.service';
import { LogisticsAction } from './logistics.action';
import { Navigate } from '@ngxs/router-plugin';
import * as immutable from 'object-path-immutable';
import { mergeMap } from 'rxjs';
import { MessageAction } from '@shared/lib/store/message/message.action';
import { uuid } from '@shared/lib/utils/utils';
import * as _ from 'lodash';

export interface LogisticsStateModel {
  list: any;
  bill: any;
}

@State<LogisticsStateModel>({
  name: 'logistics',
  defaults: {
    list: [],
    bill: [],
  },
})
@Injectable({
  providedIn: 'root',
})
export class LogisticsState implements NgxsAfterBootstrap {

  constructor(
      private logisticsService: LogisticsService,
  ) {
  }

  ngxsAfterBootstrap(ctx: StateContext<any>): void {
    // ctx.patchState({list: []});
    this.logisticsService.init();
  }

  @Action(LogisticsAction.GetBillMessage)
  GetBillMessage(ctx: StateContext<LogisticsStateModel>, {data}: LogisticsAction.GetBillMessage) {
    let bill = {
      id: uuid(), data, status: 1,
      createTime: new Date().getTime(),
    };
    ctx.setState(immutable.push(ctx.getState(), ['list'], bill));
    ctx.patchState({bill});
    return ctx.dispatch(new Navigate(['/plugin/logistics/bill']))
        .pipe(mergeMap(() => ctx.dispatch(new MessageAction.Send({key: 'Logistics_BillCallback'}))));
  }

  @Action(LogisticsAction.Delete)
  Delete(ctx: StateContext<LogisticsStateModel>, {data}: LogisticsAction.Delete) {
    let state = ctx.getState();
    let idx = _.findIndex(state.list, (s: any) => s.id === data.id);
    if (idx !== -1) ctx.setState(immutable.del(state, ['list', idx]));
  }

  @Action(LogisticsAction.Mark)
  Mark(ctx: StateContext<LogisticsStateModel>, {data, status}: LogisticsAction.Mark) {
    let state = ctx.getState();
    let idx = _.findIndex(state.list, (s: any) => s.id === data.id);
    if (idx !== -1) ctx.setState(immutable.set(state, ['list', idx, 'status'], status));
  }
}
